package com.probiz.estore.product.dao.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.probiz.estore.common.model.product.ProductType;
import com.probiz.estore.common.model.product.ProductTypeBrand;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.product.dao.ProductTypeBrandDao;

/**
 * Dao implementation for ProductTypeBrand.
*/
public class ProductTypeBrandDaoImpl extends HibernateGenericDaoImpl<ProductTypeBrand> implements ProductTypeBrandDao {

	public void deleteByProductType(Integer productTypeId) {
		List<ProductTypeBrand> list = listByProperty("productType.productTypeId", productTypeId);
		if (list != null && list.size() > 0) {
			for (ProductTypeBrand entity : list) {
				delete(entity);
			}
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.dao.ProductTypeBrandDao#getByProductTypIdAndBrandId(java.lang.Integer, java.lang.Integer)
	 */
	public ProductTypeBrand getByProductTypIdAndBrandId(Integer productTypeId, Integer brandId){
		List<ProductTypeBrand> list = this.findByHql("from ProductTypeBrand pb where pb.productType.productTypeId =? and pb.brand.brandId=?", productTypeId,brandId);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.dao.ProductTypeBrandDao#saveProductTypeBrandsFromArrays(com.probiz.estore.common.model.product.ProductType, java.lang.String[])
	 */
	public List<String> saveProductTypeBrandsFromArrays(ProductType productType, String[] brandIds){
			List<String> newBrandIdList = new ArrayList<String>();
			//删除关联品牌
			List<String> brandIdList= Arrays.asList(brandIds);
			Set<ProductTypeBrand> formerProductTypeBrandList=productType.getProductTypeBrands();//原来的关联
			for (ProductTypeBrand productTypeBrand : formerProductTypeBrandList) {
				if(!brandIdList.contains(productTypeBrand.getBrand().toString())){
					delete(productTypeBrand);
				}
			}
			//增加或者修改关联品牌
			for (int i = 0; i < brandIds.length; i++) {
				ProductTypeBrand productTypeBrand;
				productTypeBrand = getByProductTypIdAndBrandId(productType.getProductTypeId(),Integer.valueOf(brandIds[i]));
				if(null == productTypeBrand){
					//case:新增
					productTypeBrand = new ProductTypeBrand();
				}
				productTypeBrand.setProductType(productType);
				productTypeBrand.setBrandId(Integer.valueOf(brandIds[i]));
				productTypeBrand.setSortOrder(i);
				save(productTypeBrand);
				newBrandIdList.add(productTypeBrand.getProductTypeBrandId().toString());
			}
			return newBrandIdList;
	}

}
